<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <div class="max-w-6xl mx-auto p-6">
      <!-- 头部导航 -->
      <div class="mb-8">
        <h1 class="text-4xl font-bold text-gray-800 mb-4">{{ currentChapter }}讲义</h1>
      </div>

      <!-- 讲义列表 -->
      <div v-if="!selectedLecture" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto">
        <div v-for="lecture in lectures" :key="lecture.name"
          class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 cursor-pointer transform hover:scale-105"
          @click="selectLecture(lecture)">
          <div class="p-6">
            <h3 class="text-xl font-semibold text-gray-800 mb-2">{{ lecture.title }}</h3>
            <p class="text-gray-600 text-sm">{{ lecture.name }}</p>
          </div>
        </div>
      </div>

      <!-- 讲义内容 -->
      <div v-if="selectedLecture" class="bg-white rounded-lg shadow-lg p-8">
        <div class="mb-6 flex items-center justify-between">
          <h2 class="text-2xl font-bold text-gray-800">{{ selectedLecture.title }}</h2>
          <button @click="selectedLecture = null"
            class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-medium transition-colors">
            返回列表
          </button>
        </div>

        <!-- PDF 内容 -->
        <div v-if="isPdfFile(selectedLecture.name)" class="w-full">
          <VuePdfEmbed :source="selectedLecture.path" class="w-full border border-gray-300 rounded-lg"
            style="min-height: 600px;" />
        </div>

        <!-- Markdown 内容 -->
        <div v-else>
          <div class="flex gap-6 h-[600px]">
            <!-- 左侧目录 -->
            <div v-if="tableOfContents.length > 0 && !isTocCollapsed" class="w-64 flex-shrink-0 transition-all duration-300">
              <div class="h-full overflow-y-auto border border-gray-200 rounded-lg p-4 bg-gray-50">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-semibold text-gray-800">目录</h3>
                  <button @click="toggleToc" class="p-1 hover:bg-gray-200 rounded transition-colors" title="折叠目录">
                    <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                  </button>
                </div>
                <nav class="space-y-1">
                  <div v-for="item in tableOfContents" :key="item.id" :class="[
                    'block px-3 py-2 text-sm rounded-md cursor-pointer transition-colors',
                    item.level === 1 ? 'font-semibold text-gray-900 hover:bg-blue-100' : '',
                    item.level === 2 ? 'ml-4 text-gray-700 hover:bg-blue-50' : '',
                    item.level === 3 ? 'ml-8 text-gray-600 hover:bg-blue-50' : '',
                    item.level >= 4 ? 'ml-12 text-gray-500 hover:bg-blue-50' : ''
                  ]" @click="scrollToHeading(item.id)">
                    {{ item.text }}
                  </div>
                </nav>
              </div>
            </div>

            <!-- 折叠状态下的展开按钮 -->
            <div v-if="tableOfContents.length > 0 && isTocCollapsed" class="flex-shrink-0">
              <button @click="toggleToc" class="h-full w-8 bg-gray-100 hover:bg-gray-200 border border-gray-200 rounded-lg flex items-center justify-center transition-colors" title="展开目录">
                <svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </button>
            </div>

            <!-- 右侧内容 -->
            <div class="flex-1">
              <div ref="contentContainer" class="h-full overflow-y-auto border border-gray-200 rounded-lg p-4">
                <div id="content" v-if="lectureContent" class="prose prose-lg max-w-none" v-html="lectureContent"></div>
                <div v-else class="text-center py-8">
                  <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
                  <p class="mt-4 text-gray-600">加载中...</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { marked } from 'marked'
import VuePdfEmbed from 'vue-pdf-embed'
import Prism from 'prismjs'
import 'prismjs/themes/prism.css'
// 导入常用语言支持（移除有依赖问题的组件）
import 'prismjs/components/prism-javascript'
import 'prismjs/components/prism-typescript'
import 'prismjs/components/prism-css'
import 'prismjs/components/prism-json'
import 'prismjs/components/prism-python'
import 'prismjs/components/prism-java'
import 'prismjs/components/prism-csharp'
import 'prismjs/components/prism-sql'
import 'prismjs/components/prism-bash'
import 'prismjs/components/prism-markdown'

// 配置marked.js以支持Prism.js语法高亮
marked.setOptions({
  highlight: function(code: string, lang: string) {
    if (lang && Prism.languages[lang]) {
      try {
        return Prism.highlight(code, Prism.languages[lang], lang)
      } catch (error) {
        console.warn('语法高亮失败:', error)
        return code
      }
    }
    return code
  }
})

interface Lecture {
  name: string
  title: string
  path: string
}

// 注册组件
const components = {
  VuePdfEmbed
}

const router = useRouter()
const route = useRoute()

const currentChapter = ref('')
const lectures = ref<Lecture[]>([])
const selectedLecture = ref<Lecture | null>(null)
const lectureContent = ref('')
const tableOfContents = ref<Array<{ id: string, text: string, level: number }>>([])
const contentContainer = ref<HTMLElement | null>(null)
const isTocCollapsed = ref(false)

const goBack = () => {
  router.push('/select')
}

const toggleToc = () => {
  isTocCollapsed.value = !isTocCollapsed.value
}

const isPdfFile = (filename: string) => {
  return filename.toLowerCase().endsWith('.pdf')
}

// 生成目录
const generateTableOfContents = (htmlContent: string) => {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlContent, 'text/html')
  const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6')

  const toc: Array<{ id: string, text: string, level: number }> = []

  headings.forEach((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    const text = heading.textContent?.trim() || ''
    const id = `heading-${index}`

    // 为标题添加 ID
    heading.id = id

    if (text) {
      toc.push({ id, text, level })
    }
  })

  return { toc, modifiedHtml: doc.body.innerHTML }
}

// 滚动到指定标题
const scrollToHeading = (headingId: string) => {
  if (!contentContainer.value) return

  const targetElement = contentContainer.value.querySelector(`#${headingId}`)
  if (targetElement) {
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

const selectLecture = async (lecture: Lecture) => {
  selectedLecture.value = lecture
  lectureContent.value = ''
  tableOfContents.value = []

  // 如果是PDF文件，不需要加载内容
  if (isPdfFile(lecture.name)) {
    return
  }

  // 处理Markdown文件
  try {
    const response = await fetch(lecture.path)
    if (response.ok) {
      const markdown = await response.text()
      const htmlContent = await marked(markdown)

      // 生成目录并修改HTML内容
      const { toc, modifiedHtml } = generateTableOfContents(htmlContent)
      tableOfContents.value = toc
      lectureContent.value = modifiedHtml
      
      // 等待DOM更新后应用语法高亮
      await nextTick()
      try {
        Prism.highlightAll()
      } catch (error) {
        console.warn('语法高亮应用失败:', error)
      }
    } else {
      lectureContent.value = '<p class="text-red-500">无法加载讲义内容</p>'
    }
  } catch (error) {
    console.error('加载讲义失败:', error)
    lectureContent.value = '<p class="text-red-500">加载讲义时发生错误</p>'
  }
}

const loadLectures = async () => {
  const chapter = route.params.chapter as string
  currentChapter.value = chapter

  // 根据章节号获取对应的讲义文件
  const chapterMap: Record<string, string> = {
    '第1次课': 'chap01',
    '第2次课': 'chap02',
    '第3次课': 'chap03',
    '第4次课': 'chap04',
    '第5次课': 'chap05'
  }

  const chapterDir = chapterMap[chapter]
  if (!chapterDir) {
    console.error('未知的章节:', chapter)
    return
  }

  // 根据实际文件结构配置讲义列表
  const lectureFiles = {
    'chap01': [
      { name: '第01课-绪论.pdf', title: '第01课-绪论', path: `/chap01/第01课-绪论.pdf` },
      { name: '第1次课第1学时_教案.md', title: '第1次课第1学时教案', path: `/chap01/第1次课第1学时_教案.md` },
      { name: '第1次课第2学时_教案.md', title: '第1次课第2学时教案', path: `/chap01/第1次课第2学时_教案.md` }
    ],
    'chap02': [
      { name: '第2章第1学时_教案.md', title: '第2章第1学时教案', path: `/chap02/第1学时-VS Code.md` },
      { name: '第2章第2学时_教案.md', title: '第2章第2学时教案', path: `/chap02/第2学时-开发工具深入应用.md` },
      // { name: '第2章第3学时_教案.md', title: '第2章第3学时教案', path: `/chap02/第2章第3学时_教案.md` },
      // { name: '第2章第4学时_教案.md', title: '第2章第4学时教案', path: `/chap02/第2章第4学时_教案.md` }
    ],
    'chap03': [
      { name: '第3章第1学时_教案.md', title: '第3章第1学时教案', path: `/chap03/第3章第1学时_教案.md` },
      { name: '第3章第2学时_教案.md', title: '第3章第2学时教案', path: `/chap03/第3章第2学时_教案.md` }
    ],
    'chap04': [
      { name: '第4次课第1学时_教案.md', title: '第4次课第1学时教案', path: `/chap04/第4次课第1学时_教案.md` },
      { name: '第4次课第2学时_教案.md', title: '第4次课第2学时教案', path: `/chap04/第4次课第2学时_教案.md` },
      { name: '第4次课第3学时_教案.md', title: '第4次课第3学时教案', path: `/chap04/第4次课第3学时_教案.md` },
      { name: '第4次课第4学时_教案.md', title: '第4次课第4学时教案', path: `/chap04/第4次课第4学时_教案.md` }
    ],
    'chap05': [
      { name: '第5次课第1学时_教案.md', title: '第5次课第1学时教案', path: `/chap05/第5次课第1学时_教案.md` },
      { name: '第5次课第2学时_教案.md', title: '第5次课第2学时教案', path: `/chap05/第5次课第2学时_教案.md` },
      { name: '第5次课第3学时_教案.md', title: '第5次课第3学时教案', path: `/chap05/第5次课第3学时_教案.md` },
      { name: '第5次课第4学时_教案.md', title: '第5次课第4学时教案', path: `/chap05/第5次课第4学时_教案.md` }
    ]
  }

  lectures.value = lectureFiles[chapterDir as keyof typeof lectureFiles] || []
}

onMounted(() => {
  loadLectures()
})

watch(() => route.params.chapter, () => {
  loadLectures()
  selectedLecture.value = null
  lectureContent.value = ''
  tableOfContents.value = []
  isTocCollapsed.value = false
})
</script>

<style scoped>
:deep(table) {
  border: 1px solid #9ca3af;
  border-collapse: collapse;
}

:deep(table th),
:deep(table td) {
  border: 1px solid #9ca3af;
}

:deep(a) {
  color: #2563eb;
  text-decoration: underline;
}

/* 深度样式：为标题设置粗体 */
:deep(h1),
:deep(h2),
:deep(h3),
:deep(h4),
:deep(h5),
:deep(h6) {
  font-weight: bold;
}

/* 深度样式：为代码块添加高亮样式 */
:deep(pre) {
  background-color: #f5f5f5;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  padding: 1rem;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.5;
  margin: 1rem 0;
}

:deep(code) {
  background-color: #f1f3f4;
  color: #d73a49;
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

:deep(pre code) {
  background-color: transparent;
  color: inherit;
  padding: 0;
  border-radius: 0;
  font-size: 0.9em;
}

/* Prism.js 语法高亮样式增强 */
:deep(.token.comment),
:deep(.token.prolog),
:deep(.token.doctype),
:deep(.token.cdata) {
  color: #708090;
}

:deep(.token.punctuation) {
  color: #999;
}

:deep(.token.property),
:deep(.token.tag),
:deep(.token.boolean),
:deep(.token.number),
:deep(.token.constant),
:deep(.token.symbol),
:deep(.token.deleted) {
  color: #905;
}

:deep(.token.selector),
:deep(.token.attr-name),
:deep(.token.string),
:deep(.token.char),
:deep(.token.builtin),
:deep(.token.inserted) {
  color: #690;
}

:deep(.token.operator),
:deep(.token.entity),
:deep(.token.url),
:deep(.language-css .token.string),
:deep(.style .token.string) {
  color: #9a6e3a;
}

:deep(.token.atrule),
:deep(.token.attr-value),
:deep(.token.keyword) {
  color: #07a;
}

:deep(.token.function),
:deep(.token.class-name) {
  color: #dd4a68;
}

:deep(.token.regex),
:deep(.token.important),
:deep(.token.variable) {
  color: #e90;
}
</style>